package kz.edu.sdu.atm.client;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import kz.edu.sdu.atm.models.Request;
import kz.edu.sdu.atm.models.Response;
import kz.edu.sdu.atm.models.ResponseStatus;
import kz.edu.sdu.atm.server.ComProtocol;
import kz.edu.sdu.atm.util.Logger;

public class ComProtocolClient extends IComProtocolClient {
	Logger log = new Logger(ComProtocol.class);
	public static Pattern RESPONSE_PATTERN = Pattern
			.compile("~[a-zA-Z_-]+:[a-zA-Z0-9 .=-]*~");
	public static String REQUEST_FORMAT = "~%s:%s:%s:%s~";

	public ComProtocolClient(Scanner in, PrintWriter out) {
		this.in = in;
		this.out = out;
	}

	@Override
	public Response getResopnse(Scanner in) {
		String line = in.findInLine(RESPONSE_PATTERN);
		Response result = null;
		if (line != null) {
			line = line.substring(1, line.length() - 1);
			log.debug("got reply: " + line);
			String[] r = line.split(":");
			result = new Response(ResponseStatus.valueOf(r[0]), r[1]);
			log.debug("reply taken: " + result.toString());
		}
		return result;
	}

	@Override
	public void sendRequest(PrintWriter out, Request req) {
		StringBuffer sm = new StringBuffer();
		Iterator<Entry<String, String>> i = req.getMap().entrySet().iterator();

		while (i.hasNext()){
			Entry<String, String> e = i.next();
			sm.append(String.format("%s=%s;", e.getKey(), e.getValue()));
		}
		String m = String.format(REQUEST_FORMAT, req.getUsername(), req
				.getPassword(), req.getOperation().toString(), sm.toString());
		out.println(m);
		out.flush();
		log.debug("send request: " + m);
	}


}
